package com.ruoyi.sale.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.sale.domain.ErpGoodss;
import com.ruoyi.sale.domain.ErpOrder;
import com.ruoyi.sale.mapper.ErpOrderReturnMappers;
import com.ruoyi.sale.service.IErpOrderService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.sale.domain.ErpOrderReturns;
import com.ruoyi.sale.service.IErpOrderReturnService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static com.ruoyi.common.utils.PageUtils.startPage;

/**
 * 订单退货Controller
 *
 * @author ruoyi
 * @date 2025-04-15
 */
@RestController
@RequestMapping("/xiaoshou/refund")
public class ErpOrderReturnControllers extends BaseController
{
    @Autowired
    private IErpOrderReturnService erpOrderReturnService;

    @Autowired
    private IErpOrderService erpOrderService;

    /**
     * 查询订单退货列表
     */

    @PreAuthorize("@ss.hasPermi('xiaoshou:refund:list')")
    @GetMapping("/list")
    public TableDataInfo list(ErpOrderReturns erpOrderReturns)
    {
        startPage();
        List<ErpOrderReturns> list = erpOrderReturnService.selectErpOrderReturnList(erpOrderReturns);
        return getDataTable(list);
    }

    /**
     * 导出订单退货列表
     */
    @PreAuthorize("@ss.hasPermi('xiaoshou:refund:export')")
    @Log(title = "订单退货", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ErpOrderReturns erpOrderReturns)
    {
        List<ErpOrderReturns> list = erpOrderReturnService.selectErpOrderReturnList(erpOrderReturns);
        ExcelUtil<ErpOrderReturns> util = new ExcelUtil<ErpOrderReturns>(ErpOrderReturns.class);
        util.exportExcel(response, list, "订单退货数据");
    }

    /**
     * 获取订单退货详细信息
     */
    @PreAuthorize("@ss.hasPermi('xiaoshou:refund:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(erpOrderReturnService.selectErpOrderReturnById(id));
    }

    /**
     * 新增订单退货
     */
    @PreAuthorize("@ss.hasPermi('xiaoshou:refund:add')")
    @Log(title = "订单退货", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ErpOrderReturns erpOrderReturns)
    {
        return toAjax(erpOrderReturnService.insertErpOrderReturn(erpOrderReturns));
    }

    /**
     * 修改订单退货
     */
    @PreAuthorize("@ss.hasPermi('xiaoshou:refund:edit')")
    @Log(title = "订单退货", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ErpOrderReturns erpOrderReturns)
    {
        return toAjax(erpOrderReturnService.updateErpOrderReturn(erpOrderReturns));
    }

    /**
     * 删除订单退货
     */
    @PreAuthorize("@ss.hasPermi('xiaoshou:refund:remove')")
    @Log(title = "订单退货", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(erpOrderReturnService.deleteErpOrderReturnByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('xiaoshou:refund:audit')")
    @Log(title = "订单退货审核", businessType = BusinessType.UPDATE)
    @PutMapping("/audit")
    public AjaxResult audit(@RequestBody ErpOrderReturns erpOrderReturns) {
        if ("审核通过".equals(erpOrderReturns.getStatus())) {
            // 1. 更新退货单状态
            erpOrderReturnService.updateErpOrderReturn(erpOrderReturns);
            // 2. 同步数据到统计表
            erpOrderReturnService.syncReturnStatistics(erpOrderReturns.getId());
            return success();
        }
        return toAjax(erpOrderReturnService.updateErpOrderReturn(erpOrderReturns));
    }

    @GetMapping("/order/info/{orderId}")
    public AjaxResult getOrderInfo(@PathVariable Long orderId) {
        ErpOrder order = erpOrderService.selectErpOrderById(orderId.intValue());
        if (order == null) {
            return AjaxResult.error("订单不存在");
        }

        Map<String, Object> result = new HashMap<>();
        result.put("warehouseId", order.getWarehouseId());
        result.put("warehouseName", order.getWarehouseName());
        result.put("deptId", order.getDeptId());
        result.put("deptName", order.getDeptName());

        return AjaxResult.success(result);
    }

    @GetMapping("/order/goods/{orderId}")
    public AjaxResult getOrderGoodsByOrderId(@PathVariable Long orderId) {
        List<ErpGoodss> goodsList = erpOrderReturnService.selectByOrderId(orderId);

        // 处理数量为0的情况
        goodsList.forEach(item -> {
            if(item.getCountNum() == 0) {
                item.setCountNum(1); // 设置默认值
            }
        });

        return AjaxResult.success(goodsList);
    }

    @GetMapping("/order/list")
    public TableDataInfo listOrders(ErpOrder erpOrder) {
        startPage();
        List<ErpOrder> list = erpOrderService.selectAvailableOrderList(erpOrder);
        return getDataTable(list);
    }

}
